<template>
    <div>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" v-for="dish in dishes" :key="dish.id">
          <el-card class="box-card">
            <img :src="getDishImageUrl(dish.image_url)" class="dish-image" />
            <div class="card-content">
              <h3>{{ dish.name }}</h3>
              <p>{{ dish.description }}</p>
              <el-button size="small" type="primary" @click="editDish(dish)">修改</el-button>
              <el-button size="small" type="danger" @click="deleteDish(dish.id)">删除</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </template>
  
  <script>
  import { ElMessage } from 'element-plus';
  import apiClient from '../api';  // 确保路径正确
  
  export default {
    data() {
      return {
        dishes: []
      };
    },
    methods: {
      async fetchDishes() {
        try {
          const response = await apiClient.get('/dishes');
          this.dishes = response.data;
        } catch (error) {
          console.error('Error fetching dishes:', error);
        }
      },
      getDishImageUrl(imageUrl) {
        return imageUrl ? `${apiClient.defaults.baseURL}${imageUrl}` : `${apiClient.defaults.baseURL}/uploads/default-image.jpeg`;
      },
      editDish(dish) {
        this.$router.push({ name: 'EditDish', params: { id: dish.id } });
      },
      async deleteDish(id) {
        try {
          await apiClient.delete(`/dishes/${id}`);
          ElMessage.success('菜品删除成功!');
          this.fetchDishes();
        } catch (error) {
          console.error('Error deleting dish:', error);
          ElMessage.error('删除菜品失败.');
        }
      }
    },
    mounted() {
      this.fetchDishes();
    }
  };
  </script>
  
  <style scoped>
  .box-card {
    margin-bottom: 20px;
  }
  .dish-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
  }
  .card-content {
    text-align: center;
  }
  @media (max-width: 600px) {
    .box-card {
      margin-bottom: 10px;
    }
    .dish-image {
      height: 150px;
    }
    .el-form-item__content {
      display: flex;
      flex-direction: column;
    }
  }
  </style>